<template>
  <div>
    <div v-if="router?.query?.type !== 'view'">
      <el-input
        v-if="c.type === 'label_input'"
        v-model="saveFormData[c.prop]"
        :placeholder="$t(c.placeholder || '请输入')"
        :maxlength="c.inputType ? c.maxlength || 255 : c.maxlength || 50"
        show-word-limit
        :clearable="c.clearable || true"
        :type="c.inputType || 'text'"
        :rows="c.rows || 3"
        :disabled="c.disabled"
      ></el-input>
      <div v-else-if="c.type === 'label_multiple_input'">
        <template v-for="multiple in c.options" :key="multiple.prop">
          <el-input
            :style="{
              width: multiple.width || '50%',
              marginRight: multiple.marginRight || '0',
            }"
            v-model="saveFormData[multiple.prop]"
            :placeholder="$t(multiple.placeholder || '请输入')"
            :maxlength="
              multiple.inputType
                ? multiple.maxlength || 255
                : multiple.maxlength || 50
            "
            show-word-limit
            :clearable="multiple.clearable || true"
            :type="multiple.inputType || 'text'"
            :rows="multiple.rows || 3"
            :disabled="multiple.disabled"
          ></el-input>
        </template>
      </div>
      <el-autocomplete
        v-else-if="c.type === 'label_input_autocomplete'"
        v-model="saveFormData[c.prop]"
        :fetch-suggestions="
          (val, cb) => {
            querySearchAsync(val, cb, c);
          }
        "
        clearable
        :placeholder="$t(c.placeholder || '请输入')"
        @select="handleAutocompleteSelect($event, c)"
        @clear="handleAutocompleteClear(c)"
      />
      <div
        v-else-if="c.type === 'label_multiple_autocomplete'"
        style="display: flex"
      >
        <template v-for="multiple in c.options" :key="multiple.prop">
          <div
            :style="{
              width: multiple.width || '50%',
              marginRight: multiple.marginRight || '0',
            }"
          >
            <el-autocomplete
              v-model="saveFormData[multiple.prop]"
              :trigger-on-focus="!multiple.triggerOnFocus"
              :fetch-suggestions="
                (val, cb) => {
                  querySearchAsync(val, cb, multiple);
                }
              "
              clearable
              :placeholder="$t(c.placeholder || '请输入')"
              @select="handleAutocompleteSelect($event, multiple)"
              @clear="handleAutocompleteClear(multiple)"
            />
          </div>
        </template>
      </div>
      <div v-else-if="c.type === 'label_input_textarea_autocomplete'">
        <div style="display: flex; align-items: center">
          <el-autocomplete
            v-model="saveFormData[c.prop]"
            :fetch-suggestions="
              (val, cb) => {
                querySearchAsync(val, cb, c);
              }
            "
            clearable
            :placeholder="$t(c.placeholder || '请输入')"
            @select="handleAutocompleteSelect($event, c)"
            @clear="handleAutocompleteClear(c)"
          />
          <el-popover
            placement="top"
            trigger="click"
            width="400px"
            popper-style="min-height: 200px;"
          >
            <template #reference>
              <el-icon size="20px" style="margin-left: 5px; cursor: pointer"
                ><Edit
              /></el-icon>
            </template>
            <el-input
              v-model="saveFormData[c.prop]"
              type="textarea"
              :rows="9"
              placeholder="Please input"
            />
          </el-popover>
        </div>
      </div>
      <div v-else-if="c.type === 'label_input_select'" style="width: 100%">
        <el-row>
          <el-col :span="c.numberSpan || 12">
            <el-input-number
              style="width: 100%"
              v-model="saveFormData[c.prop]"
              :clearable="c.clearable || true"
              :disabled="c.disabled"
              :controls="c.controls || false"
              :placeholder="$t(c.placeholder || '请输入')"
              :min="c.min || 0"
              :max="c.max || 9999999"
            ></el-input-number>
          </el-col>
          <el-col :span="c.selectSpan || 12">
            <el-select-v2
              v-model="saveFormData[c.selectProp]"
              :placeholder="$t('请选择')"
              :filterable="c.filterable"
              :multiple="c.multiple"
              :options="c.options"
              :clearable="c.clearable || true"
              :props="c.props"
              collapse-tags-tooltip
              :collapse-tags="c.collapseTags || false"
              :max-collapse-tags="c.maxCollapseTags || 2"
              @change="handleSelectChange"
            >
              <template #default="{ item }">
                <span style="margin-right: 8px">{{
                  $t(
                    item.label ||
                      item.subName ||
                      item[c.props.label || "label"] ||
                      ""
                  )
                }}</span>
                <span v-if="c.showValue">
                  {{
                    $t(
                      item.value ||
                        item.subCode ||
                        item[c.props.value || "value"] ||
                        ""
                    )
                  }}
                </span>
              </template>
            </el-select-v2>
          </el-col>
        </el-row>
      </div>
      <el-input
        v-else-if="c.type === 'label_input_emp_select'"
        v-model="saveFormData[c.name || c.textProp || c.prop]"
        readonly
        clearable
        :placeholder="$t(c.placeholder || '请选择')"
        @focus="onEmpselectFocus"
      >
        <template #suffix>
          <el-icon
            class="el-input__icon"
            style="cursor: pointer"
            @click="onEmpselectFocus"
            ><Search
          /></el-icon>
        </template>
      </el-input>
      <el-switch
        v-else-if="c.type === 'label_switch'"
        v-model="saveFormData[c.prop]"
        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #dcdfe694"
        :disabled="c.disabled"
        :active-value="c.activeValue"
        :inactive-value="c.inactiveValue"
        :active-text="c.activeText"
        :inactive-text="c.inactiveText"
      />
      <div v-else-if="c.type === 'label_multiple_date'">
        <template v-for="multiple in c.options" :key="multiple.prop">
          <el-date-picker
            :style="{
              width: multiple.width || '50%',
              marginRight: multiple.marginRight || '0',
            }"
            v-model="saveFormData[multiple.prop]"
            :type="multiple.dateType || 'datetime'"
            :disabled="multiple.disabled"
            :format="multiple.format || 'YYYY-MM-DD HH:mm:ss'"
            :value-format="multiple.valueFormat || 'YYYY-MM-DD HH:mm:ss'"
            :placeholder="$t(multiple.placeholder || '请选择日期时间')"
          ></el-date-picker>
        </template>
      </div>
      <el-date-picker
        v-else-if="c.type === 'label_date'"
        v-model="saveFormData[c.prop]"
        :type="c.dateType || 'datetime'"
        :disabled="c.disabled"
        :format="c.format || 'YYYY-MM-DD HH:mm:ss'"
        :value-format="c.valueFormat || 'YYYY-MM-DD HH:mm:ss'"
        :placeholder="$t(c.placeholder || '请选择日期时间')"
      />
      <el-radio-group
        v-model="saveFormData[c.prop]"
        v-else-if="c.type === 'label_radio'"
        @change="radioChange"
      >
        <el-radio
          v-for="item in c.options"
          :key="item[c?.props?.value || 'value']"
          :value="item[c?.props?.value || 'value']"
          >{{ $t(item[c?.props?.label || "label"]) }}</el-radio
        >
      </el-radio-group>
      <el-checkbox-group
        v-model="saveFormData[c.prop]"
        v-else-if="c.type === 'label_checkbox'"
        @change="onChangeCheckbox"
      >
        <el-checkbox
          v-for="item in c.options"
          :key="item[c.props.value]"
          :label="$t(item[c?.props.label || 'label'])"
          :value="item[c?.props.value || 'value']"
        />
      </el-checkbox-group>
      <el-radio-group
        v-model="saveFormData[c.prop]"
        v-else-if="c.type === 'label_radio_group'"
      >
        <el-radio
          :label="item.value"
          v-for="item in c.options"
          :key="item.value"
        >
          {{ $t(item.label) }}
        </el-radio>
      </el-radio-group>
      <el-input-number
        v-else-if="c.type === 'label_number'"
        style="width: 100%"
        v-model="saveFormData[c.prop]"
        :clearable="c.clearable || true"
        :disabled="c.disabled"
        :controls="c.controls || false"
        :precision="c.precision || 0"
        :placeholder="$t(c.placeholder || '请输入')"
        :min="c.min || 0"
        :max="c.max || 9999999"
      />
      <RemoteSelect
        v-else-if="c.type === 'remote_select'"
        :params="c?.params"
        :names="saveFormData[c.prop]"
        :multiple="c?.multiple"
        :api-module="c?.apiModule"
        :disabled="c?.disabled"
        @handle-remote-change="
          (val, data) => {
            handleRemoteChange(val, data);
            saveFormData[c.prop] = val;
          }
        "
        @handleClear="handleRemoteClear"
      />
      <div v-else-if="c.type === 'remote_select_input'">
        <el-row>
          <el-col :span="c?.remoteSpan || 16">
            <RemoteSelect
              :params="c?.params"
              :names="saveFormData[c.prop]"
              :multiple="c?.multiple"
              :api-module="c?.apiModule"
              :disabled="c?.disabled"
              @handle-remote-change="
                (val, data) => {
                  handleRemoteChange(val, data);
                  saveFormData[c.prop] = val;
                }
              "
              @handleClear="handleRemoteClear"
            />
          </el-col>
          <el-col :span="c?.detailedSpan || 8">
            <el-input
              v-model="saveFormData[c.detailedProp]"
              :disabled="c?.detailedDisabled"
              type="text"
              :placeholder="$t('请输入')"
            />
          </el-col>
        </el-row>
      </div>
      <div v-else-if="c.type === 'label_multiple_number'">
        <el-row>
          <el-col
            v-for="item in c?.options"
            :key="item.prop"
            :span="item?.remoteSpan || 4"
          >
            <el-input-number
              style="width: 100%"
              v-model="saveFormData[item.prop]"
              :clearable="item.clearable || true"
              :disabled="item.disabled"
              :controls="item.controls || false"
              :precision="item.precision || 0"
              :placeholder="$t(item.placeholder || '请输入')"
              :min="item.min || 0"
              :max="item.max || 9999999"
            >
              <template #suffix>
                <span>{{ $t(item.unit || "") }}</span>
              </template>
            </el-input-number>
          </el-col>
        </el-row>
      </div>
      <div v-else-if="c.type === 'label_province_city_area_input'">
        <el-row>
          <el-col :span="c?.remoteSpan || 16">
            <ProvinceCityArea
              v-model:propSelectCode="saveFormData[c.propSelectCode]"
              v-model:prop="saveFormData[c.prop]"
              :propsSelect="c.propsSelect"
              :propSelectPlaceholder="c.propSelectPlaceholder"
              :clearable="c.clearable"
              :multiple="c.multiple"
              :cascaderProps="c.props"
              :placeholder="c.placeholder"
              @onPropSelectClose="onPropSelectClose"
              @onPropSelectChange="onPropSelectChange"
              @onCascaderClose="onCascaderClose"
              @onCascaderChange="onCascaderChange"
            >
            </ProvinceCityArea>
          </el-col>
          <el-col :span="c?.detailedSpan || 8">
            <el-input
              v-model="saveFormData[c.detailedProp]"
              :disabled="c?.detailedDisabled"
              type="text"
              :placeholder="$t('请输入')"
            />
          </el-col>
        </el-row>
      </div>
      <el-select-v2
        v-else-if="c.type === 'label_select'"
        v-model="saveFormData[c.prop]"
        :placeholder="$t(c.placeholder || '请选择')"
        :filterable="c.filterable"
        :multiple="c.multiple"
        :options="c.options"
        :clearable="c.clearable || true"
        :props="c.props"
        collapse-tags-tooltip
        :collapse-tags="c.collapseTags || false"
        :max-collapse-tags="c.maxCollapseTags || 2"
        style="width: 100%"
        @change="handleSelectChange"
      >
        <template #default="{ item }">
          <span style="margin-right: 8px">{{
            $t(
              item.label || item.subName || item[c.props.label || "label"] || ""
            )
          }}</span>
          <span v-if="c.showValue">
            {{
              $t(
                item.value ||
                  item.subCode ||
                  item[c.props.value || "value"] ||
                  ""
              )
            }}
          </span>
        </template>
      </el-select-v2>
      <el-popover
        v-else-if="c.type === 'label_tree'"
        v-model:visible="c.visible"
        placement="bottom"
        :width="330"
        trigger="click"
        :teleported="true"
      >
        <el-tree-v2
          ref="treeRef"
          style="width: 100%"
          :data="c.treeDate"
          :props="c.props"
          default-expand-all
          :height="c.height || 300"
          :show-checkbox="c.showCheckbox"
          :check-strictly="c.checkStrictly"
          :filter-method="(query, node) => filterMethod(query, node)"
          :expand-on-click-node="false"
          :current-node-key="saveFormData[c.code]"
          @node-click="handleNodeClick"
        >
          <template #default="{ node }">
            <span>{{ $t(node.label || "") }}</span>
          </template>
        </el-tree-v2>
        <template #reference>
          <el-input
            v-model="saveFormData[c.prop]"
            :placeholder="$t(c.placeholder || '请输入')"
            :clearable="c.clearable || true"
            :disabled="c.disabled"
            @input="onQueryChanged($event)"
          ></el-input>
        </template>
      </el-popover>
      <el-popover
        v-else-if="c.type === 'label_site_tree'"
        v-model:visible="c.visible"
        placement="bottom"
        :width="330"
        :hide-after="200"
        trigger="click"
        @before-enter="c.treeVisible = true"
        :teleported="true"
      >
        <WebsiteTree
          ref="formWebsiteTreec"
          v-if="c.treeVisible"
          :height="c.height || '350px'"
          :cus-height="31"
          :treeSelectType="c.treeSelectType || 'radio'"
          :treeSelectBtn="c.treeSelectBtn || true"
          :rowId="c.rowId || 'id'"
          :checkedRowKeys="c.checkedRowKeys || []"
          @cancel="onTreeCancel"
          @handleSelectionChange="sizeTeerSelectionChange"
        ></WebsiteTree>
        <template #reference>
          <el-input
            v-model="saveFormData[c.textProp]"
            :placeholder="$t(c.placeholder || '请输入')"
            :disabled="c.disabled"
            :clearable="c.clearable || true"
            @input="onTabelQueryChanged($event)"
          ></el-input>
        </template>
      </el-popover>
      <div
        v-else-if="c.type === 'label_province_city_area'"
        style="width: 100%; display: flex"
      >
        <ProvinceCityArea
          v-model:propSelectCode="saveFormData[c.propSelectCode]"
          v-model:prop="saveFormData[c.prop]"
          :propsSelect="c.propsSelect"
          :propSelectPlaceholder="c.propSelectPlaceholder"
          :clearable="c.clearable"
          :multiple="c.multiple"
          :cascaderProps="c.props"
          :placeholder="c.placeholder"
          @onPropSelectClose="onPropSelectClose"
          @onPropSelectChange="onPropSelectChange"
          @onCascaderClose="onCascaderClose"
          @onCascaderChange="onCascaderChange"
        >
        </ProvinceCityArea>
      </div>
      <div v-else-if="c.type === 'label_upload'">
        <el-tag
          style="margin-right: 10px"
          v-for="(tag, tagIndex) in saveFormData[c.prop]"
          :key="tag.url"
          closable
          :disable-transitions="false"
          @click="handleLabelUpload(tag, tagIndex)"
          @close="handleClose(tag, tagIndex)"
        >
          {{ tag[c.props.label] }}
        </el-tag>
        <el-button size="small" @click="onShowupload"> + New upload </el-button>
      </div>
      <div v-else-if="c.type === 'slot'">
        <slot></slot>
      </div>
      <div v-else class="color-text" style="height: 26px">
        {{ strProp() || "-" }}
      </div>
    </div>
    <div v-else class="color-text" style="height: 26px">
      {{ strProp() || "-" }}
    </div>
    <FileUpload
      v-if="fileUploadVisible"
      v-model:visible="fileUploadVisible"
      :sourceNo="propsUpload?.sourceNo"
      :sourceNoList="propsUpload?.sourceNoList"
      :busTypeCode="propsUpload?.busTypeCode"
      :busTypeName="propsUpload?.busTypeName"
      :limit="propsUpload?.limit"
      @onConfirm="fileUploadConfirm"
    ></FileUpload>
  </div>
</template>

<script setup>
import { defineEmits } from "vue";
import { useRoute } from "vue-router";
import i18n from "@/lang/index";
const router = useRoute();
const props = defineProps({
  c: {
    type: Object,
    default: () => ({}),
  },
  formData: {
    type: Object,
    default: () => ({}),
  },
});
const emits = defineEmits([
  "update:formData",
  "handleAutocompleteSelect",
  "handleAutocompleteClear",
  "handleSelectChange",
  "onEmpselectFocus",
  "radioChange",
  "onChangeCheckbox",
  "handleRemoteChange",
  "handleRemoteClear",
  "handleNodeClick",
  "onTreeCancel",
  "sizeTeerSelectionChange",
  "onPropSelectClose",
  "onPropSelectChange",
  "onCascaderClose",
  "onCascaderChange",
  "handleLabelUpload",
  "handleClose",
  "handleSelectionChange",
  "handleEditClosed",
  "onDelete",
  "onAdd",
]);
const saveFormData = computed({
  get() {
    return props.formData;
  },
  set(val) {
    emits("update:formData", val);
  },
});
const querySearchAsync = async (queryString, cb, c) => {
  if (!queryString) return cb([]);
  const params = {};
  params[c.paramsKey] = queryString;
  const fun = c.apiModule || (() => {});
  let res = await fun({
    ...params,
  });
  const data = c.options || res.data || res.rows || [];
  const arr = data.map((item) => {
    const obj = {
      ...item,
    };
    if (!c.labelKey) {
      obj["value"] = obj[c.value];
    } else {
      const strArr = [];
      for (const key in c.labelKey) {
        obj[key] && strArr.push(obj[key]);
      }
      obj["value"] = strArr.join(c.joinStr || ",");
    }
    return {
      ...obj,
    };
  });
  cb(arr);
};
const treeRef = ref();
const onQueryChanged = (query) => {
  treeRef.value[0].filter(query);
};
const filterMethod = (query, node) => {
  return node[props.c.props.label].includes(query);
};
const handleAutocompleteSelect = (val) => {
  emits("handleAutocompleteSelect", val, props.c);
};
const handleAutocompleteClear = () => {
  emits("handleAutocompleteClear", props.c);
};
const handleSelectChange = (val) => {
  emits("handleSelectChange", val, props.c);
};
const onEmpselectFocus = () => {
  emits("onEmpselectFocus", props.c);
};
const radioChange = (val) => {
  emits("radioChange", val, props.c);
};
const onChangeCheckbox = (val) => {
  emits("onChangeCheckbox", val, props.c);
};
const handleRemoteChange = (val, data) => {
  emits("handleRemoteChange", val, data, props.c);
};
const handleRemoteClear = () => {
  emits("handleRemoteClear", "", props.c);
};
const handleNodeClick = (val) => {
  emits("handleNodeClick", val, props.c);
};
const formWebsiteTreec = ref();
const onTabelQueryChanged = (query) => {
  formWebsiteTreec.value[0].searchEvent(query);
};
const onTreeCancel = () => {
  emits("onTreeCancel", props.c);
};
const sizeTeerSelectionChange = (val) => {
  emits("sizeTeerSelectionChange", val, props.c);
};
const onPropSelectClose = () => {
  emits("onPropSelectClose", props.c);
};
const onPropSelectChange = (val, data) => {
  emits("onPropSelectChange", val, data, props.c);
};
const onCascaderClose = () => {
  emits("onCascaderClose", props.c);
};
const onCascaderChange = (data, val) => {
  emits("onCascaderChange", data, val, props.c);
};
const handleLabelUpload = (val, index) => {
  emits("handleLabelUpload", val, index, props.c);
};
const handleClose = (val, index) => {
  emits("handleClose", val, index, props.c);
};
const handleSelectionChange = (val) => {
  emits("handleSelectionChange", val, props.c);
};
const handleEditClosed = (row, rowIndex, resolve, reject, c, xGrid) => {
  emits("handleEditClosed", row, rowIndex, resolve, reject, c, xGrid);
};
const onDelete = () => {
  emits("onDelete", props.c);
};
const onAdd = (c, index) => {
  emits("onDelete", props.c, index);
};
const propsUpload = ref({});
const fileUploadVisible = ref(false);
const fileUploadConfirm = (data) => {
  saveFormData.value[propsUpload.value.prop] = data;
};
const onShowupload = () => {
  const c = props.c;
  propsUpload.value = {
    sourceNo: saveFormData.value[c.sourceNo],
    prop: c.prop,
    sourceNoList: saveFormData.value[c.prop],
    ...c.props,
  };
  fileUploadVisible.value = true;
};
const strProp = () => {
  const c = props.c;
  const str = [];
  const value = c.name
    ? saveFormData.value[c.name]
    : saveFormData.value[c.prop];
  if (!c.options && !c.apiModule) {
    if (typeof value === "string" || typeof value === "number") {
      str.push(value);
    } else if (Array.isArray(value)) {
      value.forEach((item, index) => {
        const listStr = item?.[props?.c?.listKey] || "";
        if (listStr) {
          str.push(listStr);
        }
      });
    } else if (typeof value === "object" && value !== null) {
      // 处理对象类型，如果需要的话
    }
  } else {
    const selectType = [
      "label_select",
      "label_radio",
      "label_input_textarea_autocomplete",
      "remote_select_input",
      "remote_select",
      "label_input_select",
      "label_radio",
      "label_checkbox",
    ];
    const specialType = [
      "label_province_city_area_input",
      "label_province_city_area",
    ];
    if (selectType.includes(c.type)) {
      if (c?.name) {
        saveFormData.value[c.name] && str.push(saveFormData.value[c.name]);
      } else {
        c.options?.forEach((item) => {
          const toStr = Array.isArray(value) ? value : String(value);
          if (toStr && toStr.includes(item[c?.props?.value || "value"])) {
            const label = item?.[c?.props?.label || "label" || "value"] || "";
            label && str.push(label);
          }
        });
        !str.length && value && str.push(value);
      }
      saveFormData.value[c.detailedProp] &&
        str.push(saveFormData.value[c.detailedProp]);
      saveFormData.value[c.selectProp] &&
        str.push(saveFormData.value[c.selectProp]);
    } else if (specialType.includes(c.type)) {
      if (c.labelKey) {
        for (const key in c.labelKey) {
          const element = saveFormData.value[c.labelKey[key]];
          element && str.push(element);
        }
      } else {
        value && str.push(value);
      }
      if (c.detailedProp) {
        saveFormData.value[c.detailedProp] &&
          str.push(saveFormData.value[c.detailedProp]);
      }
    } else if (c?.options) {
      c.options?.forEach((item, index) => {
        const val = `${
          saveFormData.value[item?.value || item?.prop]
            ? saveFormData.value[item?.value || item?.prop]
            : props?.c?.labelKey
            ? props?.c?.labelKey[
                saveFormData.value[item?.value || item?.prop]
              ] || ""
            : ""
        }`;
        if (!val) return;
        str.push(
          `${i18n.global.t(item.label || "")}${val}${i18n.global.t(
            item.unit || ""
          )}`
        );
      });
    } else {
      value && str.push(value);
    }
  }
  return str.join(c.joinStr || "-");
};
</script>

<style lang="scss" scoped>
</style>